package net.atomarrow.inits;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import net.atomarrow.ioc.ActionContext;
import net.atomarrow.ioc.ApplicationContext;
import net.atomarrow.util.PriorityUtil;

public class InitLoadProcessor {

	private List<InitLoader> initLoaders;
	
	public InitLoadProcessor(){
		initLoaders=new ArrayList<InitLoader>();
	}
	
	/**
	 * 加载init启动项
	 * @param plugins
	 */
	public void loadInits(List<String> paths) {
        Class clazz;
        try {
        	InitLoader initLoader;
            for (String path : paths) {
                clazz = Class.forName(path);
                if(InitLoader.class.isAssignableFrom(clazz)){
                	initLoader = (InitLoader) clazz.newInstance();
                	ApplicationContext.load(initLoader);
                	initLoaders.add(initLoader);
                }
            }
            this.initLoaders = PriorityUtil.sort(initLoaders);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } 
    }
	
    public void execute(ServletContext application){
    	for(InitLoader init:initLoaders){
    		ActionContext.init(null,null,null, null);
            ActionContext.getContext().setApplication(application);
            init.load(application);
            ActionContext.destory();
    	}
    }
    
}
